<template>
  <div class="dashboard-editor-container">
    <panel :videoProp="video" :voiceProp="voice" @change="handleChange"></panel>
    <mapButton v-model="mapType"></mapButton>
      <div class="compass" :style="rotate" @click="rotateToBase"></div>
    </el-tooltip>
    <div class="zoom">
      <div class="zoom-in" @click="zoomIn">+</div>
      <div class="zoom-out" @click="zoomOut">-</div>
    </div>
    <xdh-map v-if="showMap" ref="map" type="Amap" :zoom="zoom" :min-zoom="5" :max-zoom="18" :center="center"
      @pointermove="handleMove" :layer-config="layerConfig" @ready="readyHandle" @moveend="handleMapChange">
      <!-- 地图覆盖物加弹窗 设备 start-->
      <template v-for="(item,idx) in options">
        <xdh-map-html ref="option" :key="idx" :position="item.position" @click="showPopup(item.id)">
          <div class="marker">
            <img :src="markers[item.type+'-'+item.level]" width="32" height="40">
            <div :class="'markers-label-'+item.level">{{item.name}}</div>
          </div>
        </xdh-map-html>
        <xdh-map-scale units="metric"></xdh-map-scale>
      </template>

      <template v-for="(item,idx) in options">
        <xdh-map-popup :key="idx+'p'" :position="item.position" :offset="[0,-40]" :close-on-click="false" v-show="item.popupFlag">
          <popupPanel :info="item" @hidePopup="hidePopup(item.id)" @review="handleReview(item.id,item.level,item.monitor,item.monitorItems,item.name,item.num,item.poposition,item.popupFlag,item.position,item.postr,item.sensorType,item.time,item.type)"></popupPanel>
        </xdh-map-popup>
      </template>
      <!-- 地图覆盖物加弹窗 设备 end-->
      <!-- 摄像头 start -->
      <template v-if="video" v-for="(item,idx) in camereList">
        <xdh-map-html :key="idx+'c'" :position="item.position" @click="clickCamera(item.id)">
          <div class="marker">
            <img :src="markers['0']" width="28" height="35">
            <div class="markers-label-1">{{item.name}}</div>
          </div>
        </xdh-map-html>
      </template>
    </xdh-map>
    <span style="font-size:0">{{lonlat}}</span>
    <Review ref="Review"></Review>
  </div>
</template>

<script>
  import panel from "./index/index";
  import mapButton from "./index/index/mapButton";
  import popupPanel from "./index/index/popupPanel";
  import Review from "./index/index/dialog/review";
  import mapResizeMixins from "./mapResizeMixins";
  import { XdhMap, XdhMapScale } from "xdh-map";
  import { defaults as defaultInteractions, DragRotateAndZoom } from "ol/interaction";
  import { indexListSensorCon } from "@/api/page/device.js"
  import { listDevice, indexDeviceSum } from "@/api/slope/device";
  import { indexCamera } from "@/api/slope/camera";
  import { indexAlarmSum } from "@/api/slope/alarm";
  import { getSysRunTime } from "@/api/slope/alarm";
  import { controlGlare } from "@/api/page/index";

  export default {
    name: "Index",
    mixins: [mapResizeMixins],
    components: {
      panel,
      mapButton,
      XdhMap,
      XdhMapScale,
      mapButton,
      popupPanel,
      Review
    },
    data() {
      return {
        rotate: "transform:rotate(0deg)",
        lonlat: "",
        center: [108.378179, 22.936135],
        zoom: 18,
        popupFlag: false,
        isZooming: false,
        popuoSensorId: undefined,
        showMap: true, //显示地图
        mapType: 1, //地图的类型： 1.电子地图 2.影像地图
        olMap: null,
        video: true, //视频显示开关
        voice: true, //声光设备开关
        markers: {
          "0": require("@/assets/image/markers/0.png"),
          "0-1": require("@/assets/image/markers/0-1.png"),

          "1-0": require("@/assets/image/markers/1-0.png"),
          "1-1": require("@/assets/image/markers/1-1.png"),
          "1-2": require("@/assets/image/markers/1-2.png"),
          "1-3": require("@/assets/image/markers/1-3.png"),
          "1-4": require("@/assets/image/markers/1-4.png"),
          "1-5": require("@/assets/image/markers/1-5.png"),

          "2-0": require("@/assets/image/markers/2-0.png"),
          "2-1": require("@/assets/image/markers/2-1.png"),
          "2-2": require("@/assets/image/markers/2-2.png"),
          "2-3": require("@/assets/image/markers/2-3.png"),
          "2-4": require("@/assets/image/markers/2-4.png"),
          "2-5": require("@/assets/image/markers/2-5.png"),

          "3-0": require("@/assets/image/markers/3-0.png"),
          "3-1": require("@/assets/image/markers/3-1.png"),
          "3-2": require("@/assets/image/markers/3-2.png"),
          "3-3": require("@/assets/image/markers/3-3.png"),
          "3-4": require("@/assets/image/markers/3-4.png"),
          "3-5": require("@/assets/image/markers/3-5.png")
        },
        // 设备列表
        options: [],
        // 摄像头列表
        camereList: []
      };
    },
    watch: {
      async mapType(val) {
        this.showMap = false;
        await this.$nextTick();
        this.showMap = true;
      }
    },
    computed: {
      layerConfig() {
        // 1.电子地图 2.影像地图
        let servers = {
          "1": "https://webst01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&style=6",
          "2": "http://webrd03.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}&lang=zh_cn"
        };
        return {
          Amap: {
            title: "高德",
            server: servers[this.mapType]
          }
        };
      }
    },
    created() {
      this.getCamera();
      this.getSensor();
      this.getDeviceNum();
    },
    methods: {
      // 摄像头列表
      async getCamera() {
        let self = this;
        self.loading = true;
        indexCamera({
            pageNum: 1,
            pageSize: 5,
          }).then(response => {
            let data = response.rows;
            let listCamera = [];
            for (let i = 0; i < data.length; i++) {
              let item = data[i];
              listCamera.push({
                position: ([item.device.point.lon + ',' + item.device.point.lat][0]).split(","),
                name: item.device.deviceName,
                id: item.cameraId
              });
            }
            self.camereList = listCamera;
            self.loading = false;
          })
          .catch(err => {
            self.loading = false;
          });
      },
      async getSensor() {
        let self = this;
        self.loading = true;
        indexListSensorCon().then(response => {
            let data = response.rows;
            let listSensor = [];
            for (let i = 0; i < data.length; i++) {
              let sensor = data[i];
              let device = sensor.device;
              let sensorType = sensor.sensorType;
              let point = device.point;
              let level = 0;
              if (device.state == 1) {
                if (sensor.alarmList.length > 0) {
                  level = sensor.alarmList[0].alarmLevel;
                }
              } else if (device.state == 0) {
                level = 4;
              } else if (device.state == 2) {
                level = 5;
              }
              var obj = {};
              obj.monitorItems = sensor.monitorItems;
              obj.position = [point.lon, point.lat];
              obj.name = device.deviceName;
              obj.num = device.number;
              obj.id = sensor.sensorId;
              obj.type = sensorType.sensorTypeId;
              obj.level = level;
              obj.popupFlag = false;
              obj.sensorType = sensorType.typeName;
              obj.monitor = sensor.monitorDetail;
              obj.postr = point.lon + ", " + point.lat;
              obj.time = sensor.monitorItems[0].valueTime == null ? '' : self.fomat(sensor.monitorItems[0].valueTime);
              listSensor.push(obj);
            }
            self.options = listSensor;
            self.loading = false;
          })
          .catch(err => {
            self.loading = false;
          });
      },
      async getDeviceNum() {
        indexDeviceSum().then(res => {
          console.log(res);
        });
      },
      async getAlarmNum() {
        indexAlarmSum().then(res => {
          console.log(res);
        });
      },
      readyHandle(map, mapComp) {
        this.olMap = map;
        this.initRotate();
      },
      handleChange(t, v) {
        console.log(t, v);
        var self = this;
        if (t == "voice") {
          controlGlare(v).then(res => {
            self.msgSuccess(res.msg);
          });
        }
        this[t] = v;
      },
      showPopup(id) {
        var self = this;
        self.popuoSensorId = id;
        for (var i = 0; i < self.options.length; i++) {
          var obj = self.options[i];
          if (obj.id == id) {
            if (obj.popupFlag) return;
            obj.popupFlag = true;
            self.moveTo();
          } else {
            obj.popupFlag = false;
          }
        }
      },
      moveTo() {
        var view = this.olMap.getView();
        var center = view.getCenter();
        let coordinate = [];
        coordinate.push(center[0] + 0.0000002);
        coordinate.push(center[1] + 0.0000002);
        return new Promise((resolve, reject) => {
          view.animate({
              center: coordinate,
            },
            () => {
              resolve(view)
            }
          )
        })
      },
      hidePopup(id) {
        for (var i = 0; i < this.options.length; i++) {
          var obj = this.options[i];
          if (obj.id == id) {
            obj.popupFlag = false;
          }
        }
      },
      handleReview(id, level, monitor, monitorItems, name, num, poposition, popopFlag, popsition, postr, sensorType,
        time, type) {
        this.$refs.Review.showDialog(id, level, monitor, monitorItems, name, num, poposition, popopFlag, popsition,
          postr, sensorType, time, type);
      },
      clickCamera(e) {
        this.$router.push({
          path: "/monitoring/monitor-camera",
          query: {
            id: e
          }
        });
      },
      handleMove(e) {
        this.lonlat = e.coordinate;
      },
      zoomIn() {
        if (this.isZooming) return;
        this.isZooming = true;
        this.$refs.map.zoomIn().then(res => (this.isZooming = false));
      },
      zoomOut() {
        if (this.isZooming) return;
        this.isZooming = true;
        this.$refs.map.zoomOut().then(res => (this.isZooming = false));
      },
      handleMapChange(e) {
        let {
          center,
          zoom,
          rotation
        } = e.frameState.viewState;
        this.center = center;
        this.zoom = zoom;
        this.rotate = "transform:rotate(" + (rotation * 180) / Math.PI + "deg)";
      },
      initRotate() {
        this.olMap.addInteraction(new DragRotateAndZoom());
      },
      rotateToBase() {
        this.olMap.getView().animate({
          rotation: 0
        }, {
          duration: 500
        });
        this.rotate = "transform:rotate(0deg)";
      },
      warnItemClick(item) {
        this.$refs.option[item.alarm.alarmId].$emit('click');
      },
      fomat(val) {
        return val.substring(0, 10) + " " + val.substring(11, 19);

      }
    }
  };
</script>
<style>
  .ol-overlay-container {
    z-index: 10 !important;
  }

  .ol-overlaycontainer {
    z-index: 20 !important;
  }
</style>
<style lang="scss" scoped>
  .dashboard-editor-container {
    background-color: rgb(240, 242, 245);
    position: relative;
    height: 100%;
  }

  @media (max-width: 1024px) {
    .chart-wrapper {
      padding: 8px;
    }
  }

  .xdh-map-placement is- left-bottom {
    margin: 15px;
  }

  .marker {
    cursor: pointer;
    text-align: center;

    // img {
    // 	width: 26px;
    // 	height: 31px;
    // }
    div {
      font-size: 12px;
      padding: 2px 5px;
      color: #fff;
    }

    .markers-label-0 {
      background: #64c797;
    }

    .markers-label-1 {
      background: #3492fc;
    }

    .markers-label-2 {
      background: #ff8000;
    }

    .markers-label-3 {
      background: #ff0000;
    }

    .markers-label-5 {
      background: rgb(178, 203, 231) !important;
    }

	  .markers-label-4 {
		  background: rgb(204, 204, 204);
	  }
  }

  /deep/.xdh-map-popup {
    z-index: 1;
  }

  .compass {
    user-select: none;
    position: absolute;
    z-index: 99;
    border-radius: 50px;
    width: 50px;
    height: 50px;
    border: 1px solid #ccc;
    right: 16px;
    bottom: 90px;
    background-image: url("~@/assets/image/icons/compass.png");
    cursor: pointer;
    background-size: contain;
    background-repeat: no-repeat;
  }

  .zoom {
    user-select: none;
    position: absolute;
    z-index: 99;
    border-radius: 4px;
    border: 1px solid #ccc;
    background-color: #fff;
    overflow: hidden;
    color: #666;
    font-size: 32px;
    line-height: 30px;
    right: 24px;
    bottom: 24px;
    text-align: center;

    >div {
      width: 30px;
      height: 30px;
      cursor: pointer;
    }

    &:before {
      content: "";
      display: block;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
      height: 1px;
      width: 22px;
      background-color: #ccc;
    }
  }
</style>
